<?php

namespace app\user\admin;

use app\system\admin\Admin;
use app\user\model\User as UserModel;
use app\user\model\UserGroup as GroupModel;
use app\shouyin\model\UserBalanceLog as UserBalanceLogModel;
use app\shouyin\model\UserCardLog as UserCardLogModel;
use app\shouyin\model\UserCard as UserCardModel;
use app\shouyin\model\Subscribe as SubscribeModel;
use app\shouyin\model\SubscribeProject as SubscribeProjectModel;
use app\warehouse\model\Stock as StockModel;
use app\shouyin\model\ProductOrder as ProductOrderModel;
use think\Db;
use League\Csv\Reader;
use app\shouyin\model\UserCardDetailLog as UserCardDetailLogModel;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
/**
 * 会员控制器
 * @package app\user\admin
 */
class Index extends Admin
{
    protected $hisiModel = 'User';//模型名称[通用添加、修改专用]
    protected $hisiAddScene = 'adminCreate';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    /**
     * 会员管理
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function index()
    {
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $keyword    = $this->request->param('keyword/s');
            $sb_card    = $this->request->param('sb_card/s','');
            $groupId    = $this->request->param('group_id/d');
            $operation    = $this->request->param('operation',1);
            if(!empty($sb_card)){
                $where[] = ['sb_card', 'like', '%'.$sb_card.'%'];
            }
            if ($keyword) {

                if (is_email($keyword)) {// 邮箱

                    $where[] = ['email', 'eq', $keyword];

                } elseif (is_mobile($keyword)) {// 手机号

                    $where[] = ['mobile', 'eq', $keyword];

                } elseif (is_numeric($keyword)) {// ID

                    $where[] = ['id', 'eq', $keyword];

                } else {// 用户名、昵称

                    $where[] = ['nick', 'like', '%'.$keyword.'%'];

                }

            }

            if($operation == 1){
                $data['data'] = UserModel::with('hasShop')
                                ->where($where)
                                ->page($page)
                                ->limit($limit)
                                ->order('id desc')
                                ->select();
                $UserModel = new UserModel;
                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['user_balance'] = $UserModel->getUserbalance($value['id'],1);
                    $data['data'][$key]['user_balance_zeng'] = $UserModel->getUserbalance($value['id'],2);
                    $data['data'][$key]['user_project'] = $UserModel->getUserProjectBalance($value['id']);
                    $data['data'][$key]['user_product'] = $UserModel->getUserProDuctBalance($value['id']);

                }
                $data['count'] = UserModel::where($where)->count('id');
                $data['code'] = 0;
                return json($data);
            }else if($operation == 2){
                $data = UserModel::where($where)
                                ->field('id,nick,sb_card,mobile,email,sex,vx,birthday,height,weight,shop_id,last_login_time')
                                ->order('id desc')
                                ->select()->toArray();
                $UserModel = new UserModel;
                foreach ($data as $key => $value) {
                    $data[$key]['user_balance'] = $UserModel->getUserbalance($value['id'],1);
                    $data[$key]['user_balance_zeng'] = $UserModel->getUserbalance($value['id'],2);
                    $data[$key]['user_project'] = $UserModel->getUserProjectBalance($value['id']);
                    $data[$key]['user_product'] = $UserModel->getUserProDuctBalance($value['id']);
                    $data[$key]['shop_id'] = Db::name('shop')->where('id',$value['shop_id'])->value('name');
                    $data[$key]['sex'] = $value['sex'] == 0 ? '女' : '男';
                }
                $top = ['编号','会员','会员卡号','手机号','邮箱','性别','微信','生日','身高','体重','门店','上次到店时间','会员卡','赠送会员卡','疗程卡','产品卡'];
                $csvReturn = export_csv($top,$data,'user');
                return $csvReturn;
            }

        }

        $groups = GroupModel::cache(600)->column('id,name');
        $this->assign('groups', $groups);

        return $this->fetch();
    }

    /**
     * 重置密码
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function resetPwd()
    {
        $id = $this->request->param('id/a');

        $model = new UserModel;

        if (!$model->adminResetPassword($id)) {
            return $this->error('密码重置失败');
        }

        return $this->success('密码重置成功');
    }

    /**
     * 余额明细
     */
    public function getBalanceList()
    {
        $user_id      = $this->request->param('user_id/d');
        $this->assign('user_id',$user_id);
        $this->tabData = [
            [
                'title' => '会员卡详情',
                'url' => 'user/index/getbalancelist?user_id='.$user_id,
            ],
            [
                'title' => '疗程/产品卡详情',
                'url' => 'user/index/getcardlist?user_id='.$user_id,
            ],[
                'title' => '产品购买',
                'url' => 'user/index/getproductlist?user_id='.$user_id,
            ],
            [
                'title' => '项目消费',
                'url' => 'user/index/getprojectlist?user_id='.$user_id,
            ],
        ];
        $this->assign('hisiTabData', ['menu' => $this->tabData, 'current' => 'user/index/getbalancelist?user_id='.$user_id]);
        $this->assign('hisiTabType', 3);

        // halt($user_id);
        if ($this->request->isAjax()) { 

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $sn     = $this->request->param('sn','');
            $type     = $this->request->param('type','');
            $is_give     = $this->request->param('is_give','');
            $price     = $this->request->param('price','');
            $start      = $this->request->param('start', '2000-01-01');
            $end      = $this->request->param('end','');
            if(!empty($sn)){
                $where[] = ['sn','like','%'.$sn.'%'];
            }
            if(!empty($type)){
                $where[] = ['type','=',$type];
            }
            if(!empty($is_give)){
                $where[] = ['is_give','=',$is_give];
            }
            if(!empty($price)){
                $where[] = ['price','=',$price];
            }

            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d',strtotime("+1 day"));
            }
            $where[] = ['user_id','=',$user_id];
            $data['data'] = UserBalanceLogModel::where($where)
                            ->field('*,type as type_text')
                            ->where('createtime','between',[strtotime($start),strtotime($end)])
                            ->page($page)
                            ->limit($limit)
                            ->order('id desc')
                            ->select();
            $data['count'] = UserBalanceLogModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
            $data['code'] = 0;

            return json($data);

        }
        return $this->fetch();
    }

    public function getCardList()
    {
        $user_id      = $this->request->param('user_id/d');
        $this->assign('user_id',$user_id);
        $this->tabData = [
            [
                'title' => '会员卡详情',
                'url' => 'user/index/getbalancelist?user_id='.$user_id,
            ],
            [
                'title' => '疗程/产品卡详情',
                'url' => 'user/index/getcardlist?user_id='.$user_id,
            ],[
                'title' => '产品购买',
                'url' => 'user/index/getproductlist?user_id='.$user_id,
            ],
            [
                'title' => '项目消费',
                'url' => 'user/index/getprojectlist?user_id='.$user_id,
            ],
        ];
        $this->assign('hisiTabData', ['menu' => $this->tabData, 'current' => 'user/index/getbalancelist?user_id='.$user_id]);
        $this->assign('hisiTabType', 3);


        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);


            $cid     = $this->request->param('cid','');
            $type     = $this->request->param('type','');
            $price     = $this->request->param('price','');
            $start_num     = $this->request->param('start_num','');
            $use_num     = $this->request->param('use_num','');
            $end_num     = $this->request->param('end_num','');
            $start      = $this->request->param('start', '2000-01-01');
            $end      = $this->request->param('end','');
            if(!empty($cid)){
                $where[] = ['cid','=',$cid];
            }
            if(!empty($type)){
                $where[] = ['type','=',$type];
            }
      
            if(!empty($price)){
                $where[] = ['price','=',$price];
            }
            if(!empty($start_num)){
                $where[] = ['start_num','=',$start_num];
            }
            if(!empty($use_num)){
                $where[] = ['use_num','=',$use_num];
            }
            if(!empty($end_num)){
                $where[] = ['end_num','=',$end_num];
            }

            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d',strtotime("+1 day"));
            }

            $where[] = ['userid','=',$user_id];
            $data['data'] = UserCardDetailLogModel::where($where)
                ->where('createtime','between',[strtotime($start),strtotime($end)])
                ->page($page)
                ->limit($limit)
                ->order('id desc')
                ->select();
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['userid'])->value('nick');
                $data['data'][$key]['card_name'] = Db::name('project')->where('id',$value['cid'])->value('name');
                switch ($value['type']) {
                    case 1:
                        $data['data'][$key]['type_text'] = '买入';
                        break;
                    case 2:
                        $data['data'][$key]['type_text'] = '使用';
                        break;

                    case 3:
                        $data['data'][$key]['type_text'] = '退卡';
                        break;
                    case 4:
                        $data['data'][$key]['type_text'] = '赠送';
                        break;
                }
            }
            $data['count'] = UserCardDetailLogModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');

            $data['code'] = 0;

            return json($data);

        }
        $card_arr = Db::name('project')->field('id,name')->select();
        $this->assign('card_arr',$card_arr);
        return $this->fetch();
    }

    public function getProductList()
    {
        $user_id      = $this->request->param('user_id/d');
        $this->assign('user_id',$user_id);
        $this->tabData = [
            [
                'title' => '会员卡详情',
                'url' => 'user/index/getbalancelist?user_id='.$user_id,
            ],
            [
                'title' => '疗程/产品卡详情',
                'url' => 'user/index/getcardlist?user_id='.$user_id,
            ],[
                'title' => '产品购买',
                'url' => 'user/index/getproductlist?user_id='.$user_id,
            ],
            [
                'title' => '项目消费',
                'url' => 'user/index/getprojectlist?user_id='.$user_id,
            ],
        ];
        $this->assign('hisiTabData', ['menu' => $this->tabData, 'current' => 'user/index/getbalancelist?user_id='.$user_id]);
        $this->assign('hisiTabType', 3);
       
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);


            $sn     = $this->request->param('sn','');
            $product_id     = $this->request->param('product_id','');
            $price     = $this->request->param('price','');
            $product_num     = $this->request->param('product_num','');
            $warehouse_id     = $this->request->param('warehouse_id','');
            $bak     = $this->request->param('bak','');
            $end_num     = $this->request->param('end_num','');
            $start      = $this->request->param('start', '2000-01-01');
            $end      = $this->request->param('end','');
            if(!empty($sn)){
                $where[] = ['sn','like','%'.$sn.'%'];
            }
            if(!empty($product_id)){
                $where[] = ['product_id','=',$product_id];
            }
      
            if(!empty($price)){
                $where[] = ['price','=',$price];
            }
            if(!empty($product_num)){
                $where[] = ['product_num','=',$product_num];
            }
            if(!empty($warehouse_id)){
                $where[] = ['warehouse_id','=',$warehouse_id];
            }
            if(!empty($bak)){
                $where[] = ['bak','like','%'.$bak.'%'];
            }
            if(!empty($end_num)){
                $where[] = ['end_num','=',$end_num];
            }

            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d',strtotime("+1 day"));
            }



            $where[] = ['user_id','=',$user_id];
            $where[] = ['status','=',1];

            $data['data'] = StockModel::where($where)
            ->where('detailed_type',2)
            ->where('createtime','between',[strtotime($start),strtotime($end)])
            ->page($page)
            ->limit($limit)
            ->order('id desc')
            ->select();

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['user_name1'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
                $data['data'][$key]['shop_name1'] = Db::name('shop')->where('id',$value['shop_id'])->value('name');
                $data['data'][$key]['ware_name1'] = Db::name('warehouse')->where('id',$value['warehouse_id'])->value('name');
            }
            $data['count'] = StockModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end)])->where('detailed_type',2)->count('id');
            $data['code'] = 0;
            return json($data);
        }
        $product_arr = Db::name('product')->field('id,name')->where('status',1)->select();
        $this->assign('product_arr',$product_arr);
        $warehouse_arr = Db::name('warehouse')->field('id,name')->select();
        $this->assign('warehouse_arr',$warehouse_arr);
        return $this->fetch();
    }

    public function lookProduct()
    {
        $id = $this->request->param('id');
        if(empty($id)){
            return $this->error('缺少参数！');
        }
        $goods = ProductOrderModel::where('id',$id)->value('goods');
        $this->assign('goods',json_decode($goods,true));
        return $this->fetch();
    }

    public function getProjectList()
    {
        $user_id      = $this->request->param('user_id/d');
        $this->assign('user_id',$user_id);
        $this->tabData = [
            [
                'title' => '会员卡详情',
                'url' => 'user/index/getbalancelist?user_id='.$user_id,
            ],
            [
                'title' => '疗程/产品卡详情',
                'url' => 'user/index/getcardlist?user_id='.$user_id,
            ],[
                'title' => '产品购买',
                'url' => 'user/index/getproductlist?user_id='.$user_id,
            ],
            [
                'title' => '项目消费',
                'url' => 'user/index/getprojectlist?user_id='.$user_id,
            ],
        ];
        $this->assign('hisiTabData', ['menu' => $this->tabData, 'current' => 'user/index/getbalancelist?user_id='.$user_id]);
        $this->assign('hisiTabType', 3);

        // halt($user_id);
        if ($this->request->isAjax()) {

            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $end_num     = $this->request->param('end_num','');
            $start      = $this->request->param('start', '2000-01-01');
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d',strtotime("+1 day"));
            }

            $where['user_id'] = $user_id;

            $SubscribeModel = new SubscribeModel;
            // $data['data'] = $SubscribeModel->where($where)->select();
            $data['data'] = $SubscribeModel->where($where)
                ->where('status','<>',5)
                ->where('createtime','between',[strtotime($start),strtotime($end)])
                ->page($page)
                ->limit($limit)
                ->order('id desc')
                ->select()->toArray();
            $new_data = [];
            $i = 0;
            foreach ($data['data'] as $key => $value) {
                $shop_name = Db::name('shop')->where('id',$value['shop_id'])->value('name');
                $room_name = Db::name('room')->where('id',$value['room_id'])->value('name');
                $username1 = Db::name('user')->where('id',$value['user_id'])->value('nick');
                $data['data'][$key]['project_data'] = json_decode($value['project_data'],true);
                if(!empty($data['data'][$key]['project_data'])){
                    foreach ($data['data'][$key]['project_data'] as $k => $v) {
                        if(isset($v['adviser_id'])){
                            $new_data[$i]['adviser_id'] = Db::name('system_user')->where('id',$v['adviser_id'])->value('nick');
                        }
                        $new_data[$i]['technician_ids'] = implode(',',Db::name('system_user')->where('id','in',$v['technician_ids'])->column('nick'));
                        $new_data[$i]['shop_name'] = $shop_name;
                        $new_data[$i]['room_name'] = $room_name;
                        $new_data[$i]['username1'] = $username1;
                        $new_data[$i]['sn'] = $value['sn'];
                        $new_data[$i]['createtime'] = $value['createtime'];
                        $new_data[$i]['project_name'] = $v['project_name'];
                        $new_data[$i]['num'] = $v['num'];
                        $new_data[$i]['price'] = $v['price'];
                        $new_data[$i]['is_give'] = $v['is_give'] == 2 ? '（赠送）' : '';
                        $i++;
                    }
                }

            }
            $data['data'] = $new_data;
            $data['count'] = $SubscribeModel->where($where)->where('status','<>',5)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
            $data['code'] = 0;

            return json($data);

        }
        $project_arr = Db::name('project')->field('id,name')->select();
        $this->assign('project_arr',$project_arr);
        return $this->fetch();
    }

    public function import()
    {
        $model = new \app\common\model\SystemAnnex;
        $uploadFile = $model::fileUpload();
        if($uploadFile['code'] != 1){
            return $this->axiosMsg($uploadFile['msg'],false);
        }
        $filePath = $uploadFile['data']['file'];

        $xlsx = new Xlsx;
        $spreadsheet = $xlsx->load('.'. $filePath);
        $sheet = $spreadsheet->getActiveSheet();
        $newArr = array();

        foreach ($sheet->getRowIterator(2) as $row) {
            $tmp = array();
            foreach ($row->getCellIterator() as $cell) {
                $tmp[] = $cell->getFormattedValue();
            }
            $newArr[$row->getRowIndex()] = $tmp;
        }
        /*
        $reader = Reader::createFromPath('.'.$filePath, 'r');
        $records = $reader->getRecords();
        $newArr = [];
        foreach ($records as $offset => $record) {
            // var_export($record);
            // foreach ($record as $k => $v) {
            //     $record[$k][0] = iconv("GB2312", "UTF-8//IGNORE", $v[0]);
            //     $record[$k][3] = iconv("GB2312", "UTF-8//IGNORE", $v[3]);
            //     // $record[$k][0] = mb_convert_encoding($v[0],"UTF-8" ,"auto");
            //     // $record[$k][3] = mb_convert_encoding($v[3],"UTF-8" ,"auto");
            // }

            $newArr[] = $record;
        }
        unset($newArr[0]);

        */
        $insertData = [];
        // halt($newArr);
        //
        foreach ($newArr as $k => $v) {
            $shop_id = Db::name('shop')->where('name', $v[8])->value('id');
            if(!$shop_id){
                return  $this->axiosMsg($v[8].'--门店不存在',false);
            }
            $salt = random(16, 0);
            $insertData[] = [
                'group_id' => 1,
                'nick' => $v[0],
                'username' => time().sprintf('%04s', $k),
                'mobile' => $v[1],
                'email' => $v[2],
                'password' => md5(md5('888888').$salt),
                'salt' => $salt,
                'sex' => $v[3] == '女' ? 0 : 1,
                'ctime' => time(),
                'mtime' => time(),
                'vx' => $v[4],
                'birthday' => strtotime($v[5]),
                'height' => $v[6],
                'weight' => $v[7],
                'shop_id' => $shop_id,
                'last_login_time' => strtotime($v[9]),
                'sb_card' => $v[10]
            ];
        }

        try {
            $ins = Db::name('user')->insertAll($insertData);
        } catch (\Exception $e) {
            return  $this->axiosMsg($e->getMessage(),false);
        }
        return  $this->axiosMsg('录入成功！',true);
    }
}
